<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="采购批次号" prop="purchaseNumber">
        <el-input
          v-model="queryParams.purchaseNumber"
          placeholder="请输入采购批次号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName">
        <supplier-input
          ref="supplierParams"
          :supplier-props.sync="supplierData"
        />
      </el-form-item>
      <el-form-item label="预计供货日期" prop="deliveryDate">
        <el-date-picker
          clearable
          size="small"
          v-model="queryParams.deliveryDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择预计供货日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['supplier:purchase:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supplier:purchase:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supplier:purchase:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['supplier:purchase:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="purchaseList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column
        label="采购批次号"
        align="center"
        prop="purchaseNumber" min-width="150px"
      />
      <el-table-column label="供应商名称" align="center" prop="supplierName" />
      <el-table-column
        label="预计供货日期"
        align="center"
        prop="deliveryDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额" align="center" prop="totalAmount" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat"/>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['supplier:purchase:edit']"
            v-show="scope.row.status === 0"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['supplier:purchase:remove']"
            v-show="scope.row.status === 0"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['supplier:purchase:view']"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      :fullscreen="true"
      append-to-body
    >
      <!-- <el-steps :active="active" finish-status="success">
        <el-step title="填写供货日期"></el-step>
        <el-step title="选择采购商品"></el-step>
        <el-step title="确认收货"></el-step>
      </el-steps> -->

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="采购批次号" prop="purchaseNumber">
          <el-input
            v-model="form.purchaseNumber"
            placeholder="请输入采购批次号" maxlength="48" show-word-limit  :disabled="true"
          />
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <supplier-input
            ref="supplierParams"
            :supplier-props.sync="supplierData"
            v-model="form.supplierName"
          />
        </el-form-item>
        <el-form-item label="预计供货日期" prop="deliveryDate">
          <el-date-picker
            clearable
            size="small"
            v-model="form.deliveryDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择预计供货日期"
            :disabled="showView"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="总金额" prop="totalAmount">
          {{ this.form.totalAmount }}（元）
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
            maxlength="250"
            show-word-limit
            :disabled="showView"
          />
        </el-form-item>
        <el-divider content-position="center">采购明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAddTbPurchaseDetail"
              v-show="!showView"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDeleteTbPurchaseDetail"
              v-show="!showView"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="tbPurchaseDetailList"
          :row-class-name="rowTbPurchaseDetailIndex"
          @selection-change="handleTbPurchaseDetailSelectionChange"
          ref="tbPurchaseDetail"
        >
          <el-table-column type="expand">
            <template slot-scope="props">
               <el-form label-position="left"  class="demo-table-expand">
                  <el-form-item label="商品编号">
                    <span>{{ props.row.productSn }}</span>
                  </el-form-item>
                  <el-form-item label="品牌名称">
                    <span>{{ props.row.brandDesc }} </span>
                  </el-form-item>
                  <el-form-item label="保质期限">
                    <span>{{ props.row.shelfLife }} {{ lifeTypeFormat(props.row) }}</span>
                  </el-form-item>
               </el-form>
            </template>
          </el-table-column>
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            width="50"
          />
          <el-table-column label="商品分类" align="center" prop="typeName" />
          <el-table-column label="商品名称" prop="productName" />
          <el-table-column label="规格" prop="itemName" />
          <el-table-column label="当前库存数量" prop="storeCount" min-width="100px" />
          <el-table-column label="是否包装类型" prop="isPack" :formatter="isPackFormat"/>
          <el-table-column label="采购数量" prop="qty" min-width="100px" >
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.qty"
                controls-position="right"
                @change="handleQtyChange(scope.row)"
                placeholder="请输入数量"
                size="mini"
                :step="1"
                step-strictly
                :min="1"
                :disabled="showView"
              />
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" prop="price" min-width="100px">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.price"
                controls-position="right"
                placeholder="请输入单价"
                @change="handleQtyChange(scope.row)"
                :precision="2"
                :step="0.01"
                size="mini"
                step-strictly
                :disabled="showView"
              />
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amount" />
          <el-table-column label="验货数量" prop="checkQty"  class-name="text-danger"/>
          
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm(0)" v-show="!showView">保 存</el-button>
        <el-button type="success" @click="submitForm(1)" v-show="!showView">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--选中商品组件-->
    <product-dialog
      :product-props.sync="productData"
      :handle-select="handleSelect"
      ref="productParams"
    />
  </div>
</template>

<script>
import {
  listPurchase,
  getPurchase,
  delPurchase,
  addPurchase,
  updatePurchase,
  exportPurchase,
  generateNumber,
} from "@/api/supplier/purchase";
import supplierInput from "@/views/supplier/supplier/input";
import productDialog from "@/views/supplier/product/dialog";
export default {
  name: "Purchase",
  components: {
    supplierInput,
    productDialog,
  },
  computed: {
   
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTbPurchaseDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购表格数据
      purchaseList: [],
      // 采购明细表格数据
      tbPurchaseDetailList: [],
       // 入库单状态字典
      statusOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查看标识
      showView: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        purchaseNumber: null,
        supplierId: null,
        supplierName: null,
        deliveryDate: null,
        totalAmount: null,
        orderByColumn: "id",
        isAsc: "desc"
        
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        supplierName: [
          {
            required: true,
            message: "供应商名称不能为空",
          },
        ],
        deliveryDate: [
          {
            required: true,
            message: "预计供货日期不能为空",
          },
        ],
        purchaseNumber: [
          {
            required: true,
            message: "采购批次号不能为空",
          },
        ],
      },
      supplierData: {},
      productData: {
        open: false,
        currentQtyShow: true,
        productList: [],
        //隐藏单价
        priceShow: true,
      },
      // 保质期限年月日字典
      lifeTypeOptions: [],
      // 是否包装类型字典
      typeOptions:[],
    };
  },
  created() {
    this.getList();
    this.getDicts("bus_life_type").then((response) => {
      this.lifeTypeOptions = response.data;
    });
    this.getDicts("bus_purchase_type").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_yes_no").then(response => {
      this.typeOptions = response.data;
    });
    
  },
  methods: {
    /** 查询采购列表 */
    getList() {
      this.loading = true;
      listPurchase(this.queryParams).then((response) => {
        this.purchaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        purchaseNumber: null,
        supplierId: null,
        supplierName: null,
        deliveryDate: null,
        totalAmount: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      
      };
      this.tbPurchaseDetailList = [];
      this.supplierData.supplierName = null;
      this.$refs.supplierParams.scName = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.supplierName = this.supplierData.supplierName;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    isPackFormat(row,column){
      return this.selectDictLabel(this.typeOptions, row.isPack);
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.queryParams.supplierName=null;
      this.resetForm("queryForm");
      this.supplierData.supplierName = null;

      this.$refs.supplierParams.scName = null;

      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.showView=false;
      this.form.deliveryDate=new Date();
      this.form.status = 0;
      this.$refs.productParams.queryParams.ids = [];
      this.open = true;
      this.title = "添加采购";
      generateNumber().then((response) => {
        this.form.purchaseNumber = response.msg;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPurchase(id).then((response) => {
        this.form = response.data;
        if(this.form.status!=0){
          this.msgError("已提交数据，不能修改!");
          return;
        }
        generateNumber().then((response) => {
          this.form.purchaseNumber = response.msg;
        });

        if (
          response.data.tbPurchaseDetailList != null &&
          response.data.tbPurchaseDetailList[0].id != null
        ) {
          this.tbPurchaseDetailList = response.data.tbPurchaseDetailList;
        }
        this.showView=false;
        this.supplierData.supplierName = this.form.supplierName;
        this.$refs.supplierParams.scName = this.form.supplierName;
        this.open = true;
        this.title = "修改采购";
      });
    },
    handleSelect(data) {
      data.forEach((item) => {
        this.tbPurchaseDetailList.push(item);
      });
    },
    /** 提交按钮 */
    submitForm(status) {
      let flag = true;
      let amount = 0;
      this.tbPurchaseDetailList.some((item) => {
        if (item.qty != null && item.qty != 0) {
          amount = this.$math.add(
            amount,
            this.$math.multiply(item.price, item.qty).toFixed(2)
          );
        } else {
          this.msgError(
            "【" +
              item.brandDesc +
              "的" +
              item.productName +
              item.itemName +
              "】的数量不为空"
          );

          flag = false;
          return true;
        }
      });

      if (flag) {
        this.form.totalAmount = amount;
        this.$refs["form"].validate((valid) => {
          if (valid) {
            this.form.tbPurchaseDetailList = this.tbPurchaseDetailList;
            this.form.status=status;
            if (this.form.id != null) {
              this.form.supplierId = this.supplierData.id;
              updatePurchase(this.form).then((response) => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.supplierId = this.supplierData.id;
              addPurchase(this.form).then((response) => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除采购编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delPurchase(ids);
        })
        .then((ret) => {
          if(ret.data!=null && ret.data==-1){
            this.msgError("包含已提交数据，不能删除!");
          }
          else {
            this.getList();
            this.msgSuccess("删除成功");
          }

        });
    },
    /** 采购明细序号 */
    rowTbPurchaseDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 采购明细添加按钮操作 */
    handleAddTbPurchaseDetail() {
     
      this.$refs.productParams.open = true;
      this.$refs.productParams.getProductList();
    },
    /** 采购明细删除按钮操作 */
    handleDeleteTbPurchaseDetail() {
      
      if (this.checkedTbPurchaseDetail.length == 0) {
        this.$alert("请先选择要删除的采购明细数据", "提示", {
          confirmButtonText: "确定",
        });
      } else {
        this.checkedTbPurchaseDetail.forEach((item) => {
          for (let i = 0; i < this.tbPurchaseDetailList.length; i++) {
            if (this.tbPurchaseDetailList[i].index == item.index) {
              this.tbPurchaseDetailList.splice(i, 1);
              
              var indexProduct = this.$refs.productParams.queryParams.ids.findIndex((value)=>value==item.priceId);
              
              if(indexProduct>=0){ //判断要删除的ID是否在已经勾选的范围内
                this.$refs.productParams.queryParams.ids.splice(i, 1);
              }
              
              if(item.amount!=null && item.amount !=0){
                  this.form.totalAmount=this.$math.subtract(this.form.totalAmount, item.amount).toFixed(2);
              }
              break;
            }
          }
        });




        this.checkedTbPurchaseDetail = [];
      }
    },
    /** 单选框选中数据 */
    handleTbPurchaseDetailSelectionChange(selection) {
      this.checkedTbPurchaseDetail = selection;
      
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有采购数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportPurchase(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    handleQtyChange(row) {
      // row.amount= row.marketPrice * row.qty
      row.amount = this.$math.multiply(row.price, row.qty).toFixed(2);

      let amount = 0;

      this.tbPurchaseDetailList.map((item) => {
        if (item.amount != null && item.amount != 0) {
          amount = this.$math.add(amount, item.amount);
        }
      });

      this.form.totalAmount = amount.toFixed(2);
    },
    // 保质日期 年月日
    lifeTypeFormat(row, column) {
      return this.selectDictLabel(this.lifeTypeOptions, row.shelfLifeType);
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids;
      getPurchase(id).then((response) => {
        this.form = response.data;
        if (
          response.data.tbPurchaseDetailList != null &&
          response.data.tbPurchaseDetailList[0].id != null
        ) {
          this.tbPurchaseDetailList = response.data.tbPurchaseDetailList;
        }
        this.showView = true;
        this.supplierData.supplierName = this.form.supplierName;
        this.$refs.supplierParams.scName = this.form.supplierName;
        this.open = true;
        this.title = "查看采购";
      });
    },

    // 入库单状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
  },
};
</script>
